<template>
	<view>
		<u-popup safeAreaInsetBottom :show="show" bgColor="" closeable :round="10" @close="close" mode="bottom">
			<view class="content">
				<!-- 	<view style="position: absolute;left: 0;top: 0;">
						<image src="../static/closevideo.png" style="width: 50rpx;" mode="widthFix"></image>
					</view> -->
				<view class="titleInfo">
					<view class="up">{{title}}</view>
					<!-- 	<view v-if="popnewData.issue!==null&& parseInt(indexTime.split(':')[0], 10) > 22" class="dw">
						已开奖
					</view> -->
					<view class="dw">
						下期倒计时：{{indexTime}}
					</view>
					<!-- 	<view v-else-if="popnewData.issue==null||popnewData.expect==null" class="dw">
						开奖中
					</view> -->
				</view>
				<u-scroll-list :indicator="false">
					<view
						style="margin: 0 auto;width: 100%;display: flex;white-space: nowrap;margin-top: 20rpx;justify-content: space-between;align-items: center;gap: 15rpx;">
						<view class="code-name" v-for="(item, index) in nameCode.slice(0, 6)" :key="index"
							@click="changtab(item,index)" v-if="isnmber(popnewData.opencode.split(',')[index])"
							:style="index===tabindex?'color:#fff;background-image: url(../static/kkk.png);background-repeat: no-repeat;background-size: 100% 100%;':'border: 1px #e6e4e7 solid;'">
							{{item.name}}
						</view>
						<view class=""
							v-if="isnmber(popnewData.opencode.split(',')[popnewData.opencode.split(',').length-1])">
							+
						</view>
						<view class="code-name"
							v-if="isnmber(popnewData.opencode.split(',')[popnewData.opencode.split(',').length-1])"
							v-for="(item1, index1) in nameCode.slice(nameCode.length - 1)" @click="changtab(item1,6)"
							:key="8"
							:style="6===tabindex?'color:#fff;background-image: url(../static/kkk.png);background-repeat: no-repeat;background-size: 100% 100%;':'border: 1px #e6e4e7 solid;'">
							{{item1.name}}
						</view>
					</view>
				</u-scroll-list>
				<view class="ggl-page" :style="gglbgStyle">
					<view style="">
						<view class="open_code_zone_left-content">
							<view class="open_code_zone_left-item"
								v-for="(item,index) of popnewData.opencode.split(',').slice(0, 7)"
								v-if="index==tabindex" :key="index">
								<view class="open_code_zone_left-item-number"
									:style="judgingStyle(popnewData.wave.split(',')[index])"
									style="color: #fff;">
									{{item}}
								</view>
								<!-- 	<view class="open_code_zone_left-item-zodiac">{{popnewData.zodiac.split(',')[index]}}
								</view> -->
							</view>
						</view>
						<view class="canvas" v-for="(item,index) of popnewData.opencode.split(',').slice(0, 7)"
							:style="{ zIndex: index==tabindex ? 999 : -1 }">
							<canvas style="width:560rpx;height:300rpx;" :id="`canvas${index}`" :ref="`canvas${index}`"
								:canvas-id="`canvas${index}`" @touchstart="touchstart($event,index)"
								@touchmove="touchmove($event,index)"></canvas>
						</view>
					</view>
				</view>
				<!-- <u-button style="margin-top: 50rpx;" type="primary" text="关闭" @click="colse()"></u-button> -->
			</view>
			<view style="height: 100px;"></view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapGetters
	} from 'vuex'
	export default {
		data() {
			return {
				indexTime: '23:00:00',
				Icon: require('@/static/ggl_bg.png'),
				points0: [],
				points1: [],
				points2: [],
				points3: [],
				points4: [],
				points5: [],
				points6: [],
				popnewData: {
					"issue": null,
					"opencode": "正,在,进,行,搅,珠,中",
					"zodiac": "",
					"openTime": "",
					"wave": "red,red,red,red,red,red,red",
					"info": "數據來源macaujc.com"
				},
				ctx: null,
				tabindex: 0,
				canvas: true,
				title: '',
				isprize: {
					type: 1,
					title: '下期倒计时：'
				},
				nameCode: [{
						name: '平一'
					},
					{
						name: '平二'
					},
					{
						name: '平三'
					},
					{
						name: '平四'
					},
					{
						name: '平五'
					},
					{
						name: '平六'
					},
					{
						name: '特码'
					}
				],
			}
		},
		props: {
			show: Boolean,
			pup_obj_oldam: {},
			pup_obj_newam: {},
			pup_obj_xg: {},
			puptype: '',
			new_times_obj: {},
			old_times_obj: {},
			xg_times_obj: {}
		},
		mounted() {

		},
		computed: {
			...mapState(['winningStyle']),
			gglbgStyle() {
				let color = this.popnewData.wave.split(',');
				let index = this.tabindex; // 确保 tabindex 是响应式的  
				// 检查 index 是否有效  
				if (index < 0 || index >= color.length) {
					console.error('tabindex is out of range');
					return {}; // 返回一个空对象作为默认样式  
				}
				// 构造背景图像 URL  
				let imageUrl = require(`@/static/green.png`); // 注意路径可能需要根据你的项目结构进行调整
				if (this.puptype == 'oldam') {
					// 返回样式对象  
				} else if (this.puptype == 'newam') {

				} else if (this.puptype == 'xg') {
					imageUrl = require(`@/static/red.png`);
				}
				return {
					backgroundImage: `url(${imageUrl})`,
					backgroundRepeat: 'no-repeat',
					backgroundSize: '100% 100%'
				};
				// let closeArr = ['red', 'blue', 'green']
				// if (closeArr.includes(color[index])) {
				// 	let imageUrl = require(`@/static/${color[index]}.png`); // 注意路径可能需要根据你的项目结构进行调整
				// 	// 返回样式对象  
				// 	return {
				// 		backgroundImage: `url(${imageUrl})`,
				// 		backgroundRepeat: 'no-repeat',
				// 		backgroundSize: '100% 100%'
				// 	};
				// } else {
				// 	return {}
				// }
			},
			...mapGetters(['judgingStyle'])
		},
		watch: {
			new_times_obj(n, o) {
				// console.log(n, o)
				if (this.puptype == 'newam') {
					this.indexTime = n
				}
			},
			old_times_obj(n, o) {
				// console.log(n, o)
				if (this.puptype == 'oldam') {
					this.indexTime = n
				}
			},
			xg_times_obj(n, o) {
				// console.log(n, o)
				if (this.puptype == 'xg') {
					this.indexTime = n
				}
			},
			tabindex() {},
			pup_obj_oldam(n) {
				if (this.puptype == 'oldam') {
					this.popnewData = n
				}

				console.log(n, "dsadasd")
			},
			pup_obj_newam(n) {
				if (this.puptype == 'newam') {
					this.popnewData = n
				}

				console.log(n, "dsadasd")
			},
			pup_obj_xg(n) {
				if (this.puptype == 'xg') {
					this.popnewData = n
				}
				console.log(n, "dsadasd")
			},
			show(news, old) {
				console.log(news, old, this.new_times_obj)
				this.popnewData = this[`pup_obj_${this.puptype}`]
				console.info(this.popnewData, "this.popnewData")
				if (this.puptype == 'oldam') {
					this.title = '澳门六合彩'
				} else if (this.puptype == 'newam') {
					this.title = '新澳门六合彩'
				} else if (this.puptype == 'xg') {
					this.title = '香港六合彩'
				}
				console.log(this[`pup_obj_${this.puptype}`], "this[`pup_obj_${this.puptype}`]")
				if (news) {
					setTimeout(() => {
						this.drawInit()
					})
				}
			}
		},
		methods: {
			isnmber(str) {
				// console.log(str, "ddasdasd")
				// 尝试将字符串转换为数字  
				const num = Number(str);
				// 检查转换结果是否是有限数  
				return !isNaN(num) && isFinite(num);
			},
			getTimeUntilNextTarget(targetTimeStr) {
				// 解析目标时间字符串  
				const targetTime = new Date(targetTimeStr);
				// 获取当前时间  
				const now = new Date();
				// 设置目标时间日期为当前日期（忽略目标字符串中的日期部分）  
				const todayTarget = new Date(now);
				todayTarget.setHours(targetTime.getHours(), targetTime.getMinutes(), targetTime.getSeconds(), targetTime
					.getMilliseconds());

				// 如果今天的目标时间已经过去了，则计算到明天的目标时间  
				if (todayTarget < now) {
					todayTarget.setDate(todayTarget.getDate() + 1);
				}

				// 计算两个时间之间的差值（毫秒）  
				const diff = todayTarget - now;
				return diff;
			},
			close() {
				this.$emit('close', false)
			},
			timeChange(e) {
				// console.log(e)
				this.isprize = this.getTimeStatus(e)
			},
			getTimeStatus(timeObj) {
				// 将时间转换为分钟  
				const totalMinutes =
					timeObj.days * 24 * 60 +
					timeObj.hours * 60 +
					timeObj.minutes;
				// 检查是否刚好为五分钟（或小于等于五分钟，取决于你的具体需求）  
				if (totalMinutes <= 5) {
					return {
						type: 2,
						title: '开奖中'
					};
				}

				// 检查是否刚好为23小时（这里我们假设不考虑分钟、秒和毫秒）  
				if (timeObj.hours === 23 && timeObj.minutes === 0 && timeObj.seconds === 0 && timeObj.milliseconds === 0) {
					// 注意：这个条件在实际应用中几乎不可能满足，因为毫秒数几乎总是非零的  
					// 但为了符合你的要求，我们这样写  
					return {
						type: 3,
						title: '已开奖'
					};
				}

				// 如果不满足以上条件，可以返回一个默认值或null  
				// 这里我们选择返回null，但你可以根据需要调整  
				return {
					type: 1,
					title: '下期倒计时：'
				};
			},
			changtab(e, i) {
				this.tabindex = i
				this.points = []
			},
			drawLine(type) {
				let points = this[`points${type}`];
				if (points.length < 2) return; // 至少需要两个点才能绘制一条线

				let points1 = points[points.length - 2];
				let points2 = points[points.length - 1];

				this[`ctx${type}`].beginPath();
				this[`ctx${type}`].moveTo(points1.x, points1.y);
				this[`ctx${type}`].lineTo(points2.x, points2.y);
				this[`ctx${type}`].stroke();
				this[`ctx${type}`].draw(true);
			},
			touchstart(e, type) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					x: startX,
					y: startY
				};

				// 确保每次触摸开始时都是一个新的路径
				this[`ctx${type}`].beginPath();
				this[`points${type}`] = [startPoint]; // 清除之前的点，开始新的路径
				console.log(this[`points${type}`], "this[`points${type}`]");
			},
			touchmove(e, type) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					x: moveX,
					y: moveY,
				};

				this[`points${type}`].push(movePoint);

				// 确保在每次移动时绘制一条新线段
				if (this[`points${type}`].length >= 2) {
					this.drawLine(type);
				}
			},
			// touchstart(e, type) {
			// 	let startX = e.changedTouches[0].x;
			// 	let startY = e.changedTouches[0].y;
			// 	let startPoint = {
			// 		x: startX,
			// 		y: startY
			// 	};

			// 	this[`points${type}`].push(startPoint);
			// 	this[`ctx${type}`].beginPath();
			// 	console.log(this[`points${type}`], "this[`points${type}`]")
			// },
			// touchmove(e, type) {
			// 	let moveX = e.changedTouches[0].x
			// 	let moveY = e.changedTouches[0].y
			// 	let movePoint = {
			// 		x: moveX,
			// 		y: moveY,
			// 	}

			// 	this[`points${type}`].push(movePoint)
			// 	console.log(this[`points${type}`].length, "this[`points${type}`].length >= 2")
			// 	if (this[`points${type}`].length >= 2) {
			// 		this.drawLine(type)
			// 	}

			// },
			// drawLine(type) {
			// 	let points1 = this[`points${type}`][0]
			// 	let points2 = this[`points${type}`][1]
			// 	this[`points${type}`].shift()
			// 	this[`ctx${type}`].moveTo(points1.x, points1.y)
			// 	this[`ctx${type}`].lineTo(points2.x, points2.y)
			// 	this[`ctx${type}`].setFontSize(30)
			// 	this[`ctx${type}`].setTextBaseline('middle')
			// 	this[`ctx${type}`].setFillStyle('black')
			// 	this[`ctx${type}`].setTextAlign('center')
			// 	this[`ctx${type}`].stroke()
			// 	this[`ctx${type}`].draw(true)
			// },
			async drawInit() {
				let arr = [0, 1, 2, 3, 4, 5, 6];
				let promises = arr.map(async (item) => {
					console.log(item, "dsadsa")
					this[`ctx${item}`] = uni.createCanvasContext(`canvas${item}`, this);
					const query = uni.createSelectorQuery().in(this);
					return new Promise((resolve) => {
						query
							.select(`#canvas0`)
							.fields({
								node: true,
								size: true
							})
							.exec((res) => {
								console.log(res, "dasdsadasd")
								let {
									width,
									height
								} = res[0];
								this[`ctx${item}`].drawImage(this.Icon, 8, 0, width, height);
								this[`ctx${item}`].lineWidth = 30;
								this[`ctx${item}`].lineCap = "round";
								this[`ctx${item}`].lineJoin = "round";
								this[`ctx${item}`].globalCompositeOperation =
									'destination-out';
								this[`ctx${item}`].draw(true, () => {
									// 绘制完成后的回调，但注意这里可能不是所有 canvas 都完成了  
									resolve(); // 解决当前 promise  
								});
							});
					});
				});
				// 等待所有 canvas 绘制完成  
				await Promise.all(promises);
				// uni.hideLoading(); // 所有 canvas 绘制完成后隐藏加载提示  
			},
		}
	}
</script>

<style scoped lang="scss">
	.content {
		width: 100%;
		height: auto;
		font-size: 35rpx;
		padding: 20rpx;
		position: relative;

		.ggl-page {
			width: 660rpx;
			height: 570rpx;
			// background-color: red;
			margin: 0 auto;
			// box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 10);
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			/* 阴影水平偏移 | 阴影垂直偏移 | 模糊半径 | 阴影颜色 */
			.canvas {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				// width: 100%;
				// height: 400rpx;
				z-index: 999;
				// background-color: red;
			}

			.open_code_zone_left-content {
				display: flex;
				justify-content: space-between;
				padding: 2px 5px;

				.open_code_zone_left-item {
					.open_code_zone_left-item-plus {
						height: 50px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 18px;
						color: #da0f1f;
						font-weight: bolder;
					}

					.open_code_zone_left-item-zodiac {
						font-size: 17px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-weight: 700;
					}

					.open_code_zone_left-item-number {
						width: 3.2rem;
						height: 3.2rem;
						background-color: #ccc;
						font-size: 70px;
						display: flex;
						font-family: fantasy !important;
						align-items: center;
						justify-content: center;
						color: #fff;
						text-align: center;
						line-height: 3.2rem;
						  // 修改字体大小为0.9rem
						    font-size: 0.9rem !important;
						    
						    // 如果需要在某些情况下使用70px的字体大小，可以添加一个新的类
						    &.large-font {
						      font-size: 70px !important;
						    }
					}
				}
			}

		}

		.code-name {
			flex-grow: 1;
			// width: 100%;
			display: flex;
			justify-content: center;
			text-align: center;
			font-size: 33rpx;
			border-radius: 10rpx;
			padding: 10rpx 0;
		}

		.titleInfo {
			text-align: center;

			.up {
				color: #095caf;
				font-weight: 700;
				font-size: 56rpx;
				text-align: center;
			}

			.dw {
				margin: 0 auto;
				width: 180px;
				height: 28px;
				background-image: url('../static/daojisbg.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;
				display: flex;
				font-size: 30rpx;
				margin-top: 10rpx;
				align-items: center;
				justify-content: center;
				color: #fff;
				line-height: 28px;
			}
		}
	}
</style>